<?php

namespace app\admin\controller\device;

use app\common\controller\Backend;

/**
 * 电子蓝牙锁
 *
 * @icon fa fa-circle-o
 */
class Devicelock extends Backend
{

    /**
     * Devicelock模型对象
     * @var \app\admin\model\Devicelock
     */
    protected $model = null;
    protected $searchFields = 'lockAlias,shop.name';
    protected $noNeedLogin = ['refreshLocks'];
    protected $noNeedRight = ['refreshLocks'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Devicelock;
        $this->view->assign("lockType", $this->model->lockType());

    }


    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(['shop', 'room'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {

                if ($v['is_gateway'] == 1) {
                    $list[$k]['is_gateway'] = "网关";
                } else {
                    $list[$k]['is_gateway'] = "非网关";
                }
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 编辑
     */
    public function edit($ids = null)
    {

        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;

                //是否采用模型验证
                if ($this->modelValidate) {
                    $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                    $row->validateFailException(true)->validate($validate);
                }
                $db = array();

                $shop_id = $params['shop_id'];
                $room_id = $params['room_id'];
                $is_gateway = $params['is_gateway'];
                $lockId = $params['lockId'];
                $lock = $this->model->where('room_id', $room_id)->find();
                if ($lock) {
                    $this->model->where('id', $lock['id'])->update(['room_id' => -1, 'shop_id' => -1]);
                }
                $db['shop_id'] = $shop_id;
                $db['room_id'] = $room_id;
                $db['is_gateway'] = $is_gateway;

                $this->model->where('lockId', $lockId)->update($db);


                $this->success();

            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    //刷新锁
    public function refreshLocks()
    {
        $page = $this->request->param('page');
        if (empty($page) && $page > 0) {
            $this->error('参数格式或数值不对');
        }

        $url = "https://cnapi.sciener.com/v3/lock/list";
        $tokenUrl = "https://cnapi.sciener.com/oauth2/token";
        $tokenReq = array();
        $tokenReq['clientId'] = "4122b7859d9745a2bc32cdc084ca0231";
        $tokenReq['clientSecret'] = "07aa420424861bb837f58a33867b49d7";
        $tokenReq['username'] = "18672675467";
        $tokenReq['password'] = md5("johnwang1990");

        //error_log("==req===" . json_encode($tokenReq));
        $result = $this->postCurl($tokenUrl, $tokenReq);
        $token = $result['access_token'];
        //error_log("==token===" . $token);

        $keyReq = array();
        $keyReq['accessToken'] = $token;
        $keyReq['clientId'] = "4122b7859d9745a2bc32cdc084ca0231";
        $keyReq['pageNo'] = $page;
        $keyReq['pageSize'] = 500;
        $keyReq['date'] = $this->getMillisecond();

        $result = $this->postCurl($url, $keyReq);
        if(empty($result)){
            $this->error('请求出错');
        }

        $list = $result['list'];

        $deviceLock = new \app\admin\model\Devicelock();

        // 查询现有的锁数据
        $allLock = $deviceLock->field('lockAlias,lockMac,lockId,electricQuantity')->select();

        $newInsert = array();
        foreach ($list as $v) {
            $db = array();
            $db['lockAlias'] = $v['lockAlias'];
            $db['lockMac'] = $v['lockMac'];
            $db['lockId'] = $v['lockId'];
            $db['electricQuantity'] = $v['electricQuantity'];
            $db['lockData'] = $v['lockData'];

            $is_exist = false;
            foreach ($allLock as $m){
                if($v['lockId'] == $m['lockId']){
                    $is_exist = true;
                    if($v['lockAlias'] != $m['lockAlias'] || $v['electricQuantity'] != $m['electricQuantity']){
                        $deviceLock->where('lockId', $v['lockId'])->update($db);
                    }
                }
            }
            if(!$is_exist){
                $newInsert[]=$db;
            }
        }
        if (!empty($newInsert)) {
            $deviceLock->insertAll($newInsert);
        }

        error_log("===key===" . json_encode($result));

        $returnData['code'] = 1;
        $returnData['msg'] = '成功';
        $returnData['data'] = $result;

        return json($returnData);
    }

    protected function getMillisecond()
    {
        list($s1, $s2) = explode(' ', microtime());
        return (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000);
    }

    function postCurl($url, $data)
    {
        $header = array("Expect:", "Cache-Control: no-cache", "Content-Type: application/x-www-form-urlencoded");

        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data)); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
//        $header = array('Content-Type: application/x-www-form-urlencoded');
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        $result = curl_exec($curl); // 执行操作
        $arr = json_decode($result, true);
        curl_close($curl); // 关闭CURL会话

        return $arr;
    }

}
